// pages/product-trace/product-trace.js
const request = require('../../utils/request')
const dateFormatter = require('../../utils/dateFormatter')

Page({
  data: {
    // 核查列表数据
    checkList: [],
    // 搜索关键词（批次号）
    searchKeyword: '',
    // 是否已经搜索过
    hasSearched: false,
    // 分页参数
    pageNo: 1,
    pageSize: 10,
    total: 0,
    loadingMore: false,
    // 预览相关
    showPreview: false,
    previewData: {},
    // 溯源相关
    showSourceModal: false,
    sourceId: null
  },

  // 将后端 status 映射为中文文案与颜色
  statusMap(status) {
    const sRaw = (status == null ? '' : String(status)).toLowerCase()
    if (sRaw === '审核通过' || sRaw === 'pass' || sRaw === '1') return { text: '审核通过', color: '#07C160' }
    if (sRaw === '审核拒绝' || sRaw === 'refuse' || sRaw === '2') return { text: '审核拒绝', color: '#F44336' }
    return { text: '待审核', color: '#FFA000' }
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 清空搜索
  onClearSearch() {
    this.setData({
      searchKeyword: '',
      checkList: [],
      hasSearched: false
    });
  },

  // 搜索确认
  onSearchConfirm() {
    const keyword = this.data.searchKeyword.trim();
    if (!keyword) {
      wx.showToast({
        title: '请输入批次号',
        icon: 'none'
      });
      return;
    }
    
    // 重置分页并搜索
    this.setData({
      pageNo: 1,
      checkList: [],
      hasSearched: true
    });
    this.loadApplications();
  },

  // 加载销售凭证申请列表（按批次号搜索）
  loadApplications(loadMore = false) {
    if (this.data.loadingMore) return;

    const pageNo = loadMore ? this.data.pageNo + 1 : 1;
    const pageSize = this.data.pageSize;

    if (!loadMore) {
      wx.showLoading({ title: '加载中...' });
    } else {
      this.setData({ loadingMore: true });
    }

    // 构建搜索参数：批次号 aboutOrder
    const params = { 
      pageNo, 
      pageSize,
      aboutOrder: this.data.searchKeyword.trim()
    };

    return request.get('/admin-api/system/goods-sales-licens/source', params)
      .then(res => {
        if (!loadMore) wx.hideLoading();
        if (res.code === 0 && res.data) {
          const list = Array.isArray(res.data) ? res.data : (res.data.list || res.data.items || []);
          const total = res.data.total || res.data.totalCount || (Array.isArray(res.data) ? res.data.length : 0);

          const mapped = (list || []).map(item => {
            const map = this.statusMap(item.status || item.state);
            const detailsArr = item.goodsSalesLicensDetailSaveReqVOS || item.GoodsSalesLicensDetailSaveReqVO || item.details || item.list || [];
            const firstProdName = (detailsArr && detailsArr.length > 0)
              ? (detailsArr[0].prodName || detailsArr[0].name || detailsArr[0].goodsName || '')
              : (item.productName || item.prodName || '');

            return Object.assign({}, item, {
              merchantName: item.merchantName || item.merchant || item.shopName || '',
              address: item.address || (item.merchant && item.merchant.address) || '',
              phone: item.phone || (item.merchant && item.merchant.phone) || '',
              arriveTime: dateFormatter.formatDateYMD(item.createTime) || item.createTime || '',
              judgeTime: dateFormatter.formatDateYMD(item.okDate) || item.okDate || '',
              statusText: map.text,
              statusColor: map.color,
              productName: firstProdName,
              aboutOrder: item.aboutOrder || '',
              saleCode: item.saleCode || ''
            });
          });

          const newList = loadMore ? [...this.data.checkList, ...mapped] : mapped;

          this.setData({
            checkList: newList,
            total,
            pageNo,
            loadingMore: false
          });
        } else {
          if (!loadMore) wx.hideLoading();
          this.setData({ loadingMore: false });
          wx.showToast({
            title: res.msg || '加载失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        if (!loadMore) wx.hideLoading();
        this.setData({ loadingMore: false });
        console.error('加载列表失败:', err);
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
      });
  },


  // 预览凭证
  previewDocument(e) {
    const item = e.currentTarget.dataset.item;
    
    wx.showLoading({ title: '加载中...' });
    
    request.get('/admin-api/system/goods-sales-licens/get', { id: item.id })
      .then(res => {
        wx.hideLoading();
        if (res.code === 0 && res.data) {
          const detailData = res.data;
          const detailsArr = detailData.goodsSalesLicensDetailSaveReqVOS || detailData.details || [];
          
          // 格式化申报时间 (createTime)
          const createDateParts = dateFormatter.formatToYearMonthDay(detailData.createTime)
          
          // 格式化开票时间 (审核时间 okDate)
          const okDateParts = dateFormatter.formatToYearMonthDay(detailData.okDate)
          
          this.setData({
            showPreview: true,
            previewData: {
              saleCode: detailData.saleCode || '',
              customerName: detailData.customerName || '',
              address: detailData.address || '',
              phone: detailData.phone || '',
              aboutOrder: detailData.aboutOrder || '',
              products: detailsArr.map(d => ({
                prodName: d.prodName || d.name || d.goodsName || '',
                prodCount: d.prodCount || d.count || d.quantity || ''
              })),
              isLicens: detailData.isLicens || false,
              isCheck: detailData.isCheck || false,
              createYear: createDateParts.year,
              createMonth: createDateParts.month,
              createDay: createDateParts.day,
              okYear: okDateParts.year,
              okMonth: okDateParts.month,
              okDay: okDateParts.day
            }
          });
        } else {
          wx.showToast({
            title: res.msg || '加载失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('获取详情失败:', err);
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
      });
  },

  // 关闭预览
  closePreview() {
    this.setData({
      showPreview: false,
      previewData: {}
    });
  },

  // 显示溯源弹窗
  showSourceModal(e) {
    const id = e.currentTarget.dataset.id;
    console.log('product-trace: 显示溯源弹窗, id=', id);
    if (!id) {
      wx.showToast({ title: '未找到可溯源的ID', icon: 'none' });
      return;
    }
    // 新方案：先显示弹窗，再通过组件方法加载数据
    this.setData({ showSourceModal: true }, () => {
      console.log('product-trace: 弹窗已显示，准备调用组件方法');
      // 获取组件实例并调用 open 方法
      const sourceTimeline = this.selectComponent('#sourceTimeline');
      if (sourceTimeline) {
        console.log('product-trace: 找到组件实例，调用 open 方法, id=', id);
        sourceTimeline.open(id);
      } else {
        console.error('product-trace: 未找到组件实例');
      }
    });
  },

  // 隐藏溯源弹窗
  hideSourceModal() {
    this.setData({ showSourceModal: false });
  },

  // 从时间轴预览销售凭证
  onPreviewSalesFromTimeline(e) {
    // 可以在这里处理预览销售凭证的逻辑
    console.log('预览销售凭证:', e.detail.item);
  },

  // 返回上一页
  navigateBack() {
    wx.navigateBack();
  },

  // 页面上拉触底
  onReachBottom() {
    const currentLength = this.data.checkList.length;
    if (currentLength >= this.data.total) {
      return;
    }
    this.loadApplications(true);
  },

  // 下拉刷新
  onPullDownRefresh() {
    if (this.data.searchKeyword.trim()) {
      this.setData({
        pageNo: 1,
        checkList: []
      });
      this.loadApplications().then(() => {
        wx.stopPullDownRefresh();
      });
    } else {
      wx.stopPullDownRefresh();
    }
  },

  onLoad(options) {
    // 如果有传入批次号参数，自动搜索
    if (options.aboutOrder) {
      this.setData({
        searchKeyword: options.aboutOrder,
        hasSearched: true
      });
      this.loadApplications();
    }
  }
});
